package com.kaifamiao.wendao.service;

import com.kaifamiao.wendao.dao.CustomerDao;
import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.utils.SnowflakeIdGenerator;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;

import java.time.LocalDate;

public class CustomerService {

    private CustomerDao customerDao = new CustomerDao();

    public String encrypt(final String source,final String salt){
        // 首先对原始密码进行加密
        String encrypted = DigestUtils.sha1Hex(source);
        StringBuilder builder = new StringBuilder( encrypted );
        // 在加密后的字符序列指定位置插入盐值
        builder.insert( 20, salt );
        // 获得插入盐值后的字符串
        String inserted = builder.toString();
        // 对插入盐值后的字符串进行加密
        return DigestUtils.sha1Hex( inserted );
    }

    public Boolean save(Customer customer){
        customer.setRegisterDate(LocalDate.now());
        customer.setId(SnowflakeIdGenerator.getInstance().generate());
        final String salt= RandomStringUtils.randomAlphabetic(5);
        customer.setSalt(salt);
        String password=customer.getPassword();
        password=encrypt(password,salt);
        customer.setPassword(password);
        return customerDao.save(customer);
    }

    public boolean find(String username){
        if(customerDao.find(username)!=null){
            return true;
        }
        return false;
    }
    public Customer load(Long id){
        Customer c= customerDao.find(id);
        return c;
    }

    public Customer load(String username){
        Customer c=customerDao.find(username);
        return c;
    }

    public void update(Customer customer){
        customerDao.update(customer);
    }

    public boolean remove(Long id) {
        return customerDao.remove(id);
    }

}
